package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUnlikeBehaviorimpl implements ApUnlikeBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        //判断参数,是否登录
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "未登录");
        }
        //实体类对象
        ApUnlikesBehavior behavior = new ApUnlikesBehavior();
        //根据条件查询,
        ApBehaviorEntry userIdOrEquipmentId = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        String id = userIdOrEquipmentId.getId();
        //根据实体id,文章id查询条件
        Query query = Query.query(Criteria.where("entryId").is(id).and("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior unlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        //没有查到添加一条
        if (dto.getType() == 0) {
            if (unlikesBehavior == null) {
                behavior.setCreatedTime(new Date());
                behavior.setEntryId(id);
                behavior.setArticleId(dto.getArticleId());
                behavior.setType(dto.getType());
                mongoTemplate.save(behavior);
            }
        } else if (dto.getType() == 1) {
            mongoTemplate.remove(query, ApUnlikesBehavior.class);
        }


        return ResponseResult.okResult();
    }
}
